package com.xbh.management.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbh.common.base.BaseEntity;
import com.xbh.common.utils.RedisUtils;
import com.xbh.management.mapper.DepartmentMapper;
import com.xbh.management.model.ManDepartment;
import com.xbh.management.model.ManDeptUser;
import com.xbh.management.model.ManUser;
import com.xbh.management.task.ExportFactory;
import com.xbh.management.task.SuperExport;
import com.xbh.management.task.impl.CustomerExportImpl;
import com.xbh.management.utils.TreeNodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: management-center
 * @description:
 * @author: 许宝华
 * @create: 2021-08-30 14:28
 */

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, ManDepartment> implements DepartmentService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ManDeptUserService manDeptUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private DepartmentService departmentService;
    /**
     * 分页查询，支持客户名称模糊查询
     * @param page
     * @param manDepartment
     * @return
     */
    @Override
    public IPage<ManDepartment> list(Page<ManDepartment> page, ManDepartment manDepartment) {
        LambdaQueryWrapper<ManDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManDepartment::getDeleted, manDepartment.getDeleted())
                .like(StringUtils.isNotBlank(manDepartment.getDepartmentName()), ManDepartment::getDepartmentName, manDepartment.getDepartmentName());

        Page<ManDepartment> selectPage = this.baseMapper.selectPage(page, wrapper);
        return selectPage;
    }

    @Override
    public List<ManDepartment> queryAllDept() {
        List<ManDepartment> manDepartments = this.baseMapper.selectList(null);
        List<ManDepartment> deptList = TreeNodeUtil.transformDeptData(manDepartments, "0");
        return deptList;
    }

    /**
     * 通过id删除
     * @param customerId
     */
    @Override
    public int delCustomerByid(Long departmentId) {

        return this.baseMapper.deleteCustomerById(departmentId);
    }

    /**
     * 保存
     * @param customer
     * @return
     */
    @Override
    public int saveCustomer(ManDepartment department) {
        return this.baseMapper.insert(department);
    }

    /**
     * 通过id删除，支持批量删除
     * @param customerIds
     * @return
     */
    @Override
    public int deleteByCusIds(String departmentIds) {
        String[] customerIdArray = departmentIds.split(",");
        List<String> customerIdList = Arrays.stream(customerIdArray).collect(Collectors.toList());
        return this.baseMapper.deleteCustomerByIds(customerIdList);
    }

    /**
     * 根据客户id查看客户详情
     * @param customerId
     * @return
     */
    @Override
    public ManDepartment selectCustomerById(Long departmentId) {
        ManDepartment manDepartment = this.baseMapper.selectById(departmentId);
        redisUtils.set("departmentId",departmentId.toString());
        return manDepartment;
    }

    /**
     * 修改客户
     * @param customerId
     * @return
     */
    @Override
    public int updateCustomerById(ManDepartment department) {
        return this.baseMapper.updateById(department);
    }

    /**
     * 导出客户列表
     * @param customerList
     * @return
     */
    @Override
    public String exportCustomer(List<ManDepartment> customerList) throws Exception {
        String result = "";

        //用户导出标题
        String[] headers = { "序号", "客户名称", "提交时间", "客户邮箱", "客户电话", "客户地址","客户类型"};
        //长度设置
        Integer[] customer = { 15, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35};
        //导出
        SuperExport superExport = ExportFactory.getSuperExport(CustomerExportImpl.class, "客户列表", headers, customer, customerList);
        result = superExport.call();
        return result;
    }

    /**
     * 根据多个客户id查出客户信息，支持批量查询
     * @param manCustomer
     * @return
     */
    @Override
    public List<ManDepartment> selectCustomer(String customerIds) {
        String[] customerIdArray = customerIds.split(",");
        List<String> customerIdList = Arrays.stream(customerIdArray).collect(Collectors.toList());
        List<ManDepartment> manDepartments = this.baseMapper.selectCustomerByIds(customerIdList);
        return manDepartments;
    }

    @Override
    public Page<ManUser> selectUserByDepartmentId(Page<ManUser> page, Long departmentId) {

        List<ManDepartment> manDepartments = this.baseMapper.selectList(null);
        if(ObjectUtil.isEmpty(departmentId)){
            departmentId = 252261187417685L;
        }
        List<ManDepartment> deptList = TreeNodeUtil.transformDeptData(manDepartments, departmentId.toString());
        ArrayList<String> departmentIds = new ArrayList<String>();
        ArrayList<String> idList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(deptList)){
            this.queryChildren(deptList,idList);

            return this.baseMapper.selectUserByDepartmentId(page,idList);
        }
        departmentIds.add(departmentId.toString());
        return this.baseMapper.selectUserByDepartmentId(page,departmentIds);
    }

    /**
     * 获取当前登录人的直系领导及上级领导,一个登录人可能是多个部门的共同领导
     * @param userId
     * @return
     */
    @Override
    public JSONObject queryUserByDept(Long userId) {

        LambdaQueryWrapper<ManDeptUser> deptUserWrapper = new LambdaQueryWrapper<>();
        deptUserWrapper.eq(ManDeptUser::getDeleted,new Integer(0));
        deptUserWrapper.eq(ManDeptUser::getUserId,userId);
        //查询当前用户所属部门,当前用户可能属于多个部门
        JSONObject params = new JSONObject();
        List<ManDeptUser> deptUserList = manDeptUserService.list(deptUserWrapper);
        if(CollectionUtil.isNotEmpty(deptUserList)){
            deptUserList.stream().forEach( dept ->{
                JSONObject jsonObject = new JSONObject();
                ManDepartment currentDept = departmentService.getById(dept.getDepartmentId());
                ManUser currentDeptUser = userService.getById(currentDept.getUserId());
                jsonObject.put("currentDept",currentDeptUser);
                if(ObjectUtil.isNotEmpty(currentDept.getParentId())){
                    ManDepartment parentDept = departmentService.getById(currentDept.getParentId());
                    ManUser parentDeptUser = userService.getById(parentDept.getUserId());
                    jsonObject.put("parentDeptUser",parentDeptUser);
                }
                params.put("dept",jsonObject);
            });
            return params;
        }
        return null;
    }

    /**
     * 递归获取当前树节点下的所有节点
     * @param childrenList
     * @param idList
     */
    private void queryChildren(List<ManDepartment> childrenList,ArrayList<String> idList ){

        for (ManDepartment dept : childrenList) {
            if(ObjectUtil.isNotEmpty(dept.getChildren())){
                queryChildren(dept.getChildren(),idList);
            }
            idList.add(dept.getDepartmentId().toString());

        }
    }


}
